package jpaperwork.web;

import java.util.*;

/**
 * User: fleipold
 * Date: Nov 1, 2009
 * Time: 10:05:43 PM
 */
public class Template {
    private final TemplateParser templateParser;

    public Template(String pattern){

        templateParser = new TemplateParser(pattern);


    }


    public Map<String, String> matches(String url){
        final HashMap<String, String> values = new HashMap<String, String>();

        String remainder = url;
        for (int i = 0; i < templateParser.fragments.size(); i++) {
            Fragment fragment = templateParser.fragments.get(i);
            if (fragment.getClass() == TextFragment.class) {
                final TextFragment textFragment = (TextFragment) fragment;
                if (!remainder.startsWith(textFragment.getText())) {
                    return null;
                } else {
                    remainder = remainder.substring(textFragment.getText().length());
                }

            }
            if (fragment instanceof PlaceholderFragment) {
                PlaceholderFragment placeholderFragment = (PlaceholderFragment) fragment;
                int endOfCaptureIndex = remainder.indexOf('/');
                if (endOfCaptureIndex == -1){
                    endOfCaptureIndex = remainder.length();

                }
                String capture = remainder.substring(0, endOfCaptureIndex);

                values.put(placeholderFragment.getName(), capture);
                remainder = remainder.substring(endOfCaptureIndex);
                
            }

        }
       return values;
    }




}
